<template>
    <div class="custom-tree-container">
      <h4>指标菜单</h4>
      <div class="tree-search">
        <input 
          v-model="searchText"
          placeholder="输入关键词搜索"
          class="search-input"
          @input="handleSearch"
        />
      </div>
      <div class="tree-nodes">
        <custom-tree-node 
          v-for="node in filteredTree"
          :key="node.id"
          :node="node"
          :depth="0"
          @toggle-select="handleSelect"
        />
      </div>
    </div>
  </template>
  
  <script lang="ts">
  import { Component, Vue, Prop,Watch } from 'vue-property-decorator';
  import CustomTreeNode from '@/components/Map/CustomTreeNode.vue';
  interface TreeNode {
    id: number;
    label: string;
    children?: TreeNode[];
    selected?: boolean;
    expanded?: boolean;
    visible?: boolean;
    isLeaf?: boolean; 
  }
  
  @Component({
    methods: {},
    components: {CustomTreeNode}

    })
  export default class CustomTree extends Vue {
    @Prop({ required: true }) data!: TreeNode[];
    private searchText = '';
    private selectedNodes: number[] = [];
    private filteredTree: TreeNode[] = [];
    private parentMap = new Map<number, TreeNode>();
    private defualtSelectedNodes:any = [];
    private internalData: TreeNode[] = []; // 新增：内部数据副本

    mounted() {
     // 确保初始化树数据
       this.initializeTree();
    }

   private initializeTree() {
    // 深拷贝 prop 数据
      this.internalData = JSON.parse(JSON.stringify(this.data));
      this.initTreeData(this.internalData);
      this.filterTree();
    }

      // 初始化树数据（添加isLeaf标识）
  private initTreeData(nodes: TreeNode[],parent? : TreeNode) {

    nodes.forEach(node => {
      node.selected = false;
      node.isLeaf = !node.children || node.children.length === 0;
      if(parent){
        this.parentMap.set(node.id, parent);
      }
     
      if (node.children) {
        this.initTreeData(node.children,node);
      }
      if(node.label == "通用指标"){
         this.defualtSelectedNodes.push(node);
         node.selected = true;
         node.children?.forEach(child => {
          child.selected = true;
          this.selectedNodes.push(child.id);
         });
        this.$emit('selection-change', this.selectedNodes);
      }
    });
  }
  
    // 深度优先搜索过滤
  private filterTree() {
   const search = this.searchText.trim();
    if (!search) {
      // 无搜索条件时显示完整树
      this.filteredTree = this.internalData;
      return;
    }

    const filterFn = (nodes: TreeNode[]): TreeNode[] => {
      return nodes.filter(node => {
        const isMatch = node.label.includes(search);
        const children = node.children ? filterFn(node.children) : [];
        
        // 克隆节点避免修改原始数据
        const filteredNode = { ...node };
        filteredNode.children = children;
        filteredNode.expanded = isMatch || children.length > 0;
        
        return isMatch || children.length > 0;
      });
    };
    
    this.filteredTree = this.internalData.length ? filterFn(this.internalData) : [];
}
  
    private handleSearch() {
      this.filterTree();
    }

    private selectNode(node: TreeNode) {
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => this.selectNode(child));
      } else {
        // 仅叶子节点加入选择列表
        if (!this.selectedNodes.includes(node.id)) {
          this.selectedNodes.push(node.id);
        }
      }
    }
  
    private handleSelect(node: TreeNode) {
 
      if(!node.isLeaf){
          node.children?.forEach(child => {
          if (child.children) {
           
            child.selected = node.selected
            if(child.selected) {
              this.selectNode(child);
            }
          }
        });
        this.$emit('selection-change', this.selectedNodes);
        return;
      } 

      const index = this.selectedNodes.indexOf(node.id);

      if (index === -1) {
        this.selectedNodes.push(node.id);
      } else {
        this.selectedNodes.splice(index, 1);
      }
      this.$emit('selection-change', this.selectedNodes);
    }

    @Watch('data', { immediate: true, deep: true })
    onDataChange(newData: TreeNode[]) {
       this.initializeTree();
    }

    @Watch('defualtSelectedNodes')
    defualtSelectedNodesHandler(newData: TreeNode[]) {
      if(newData && newData.length > 0) {
        this.defualtSelectedNodes = newData;
      }
    }
  }
  </script>
  <style scoped>
  .custom-tree-container {
    max-height: 60vh;
    overflow-y: auto;
  }
  
  .tree-search {
    padding: 8px;
    border-bottom: 1px solid #eee;
  }
  
  .search-input {
    width: 90%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .tree-node {
    padding: 4px 0;
  }
  
  .node-content {
    display: flex;
    align-items: center;
    padding: 4px 0;
    cursor: pointer;
    transition: background 0.3s;
  }
  
  .node-content:hover {
    background: #f5f7fa;
  }
  
  .checkbox {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    margin-right: 8px;
    position: relative;
  }
  
  .checkbox.checked::after {
    content: '';
    position: absolute;
    left: 4px;
    top: 1px;
    width: 5px;
    height: 10px;
    border: solid #409eff;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
  }
  
  .label {
    flex: 1;
    user-select: none;
  }
  
  .expand-icon {
    width: 20px;
    text-align: center;
    margin-left: 8px;
  }
  
  .children {
    margin-left: 12px;
  }
  </style>